﻿@using PMS.Web.FrontUI
@using PMS.Web.Models.NaviMenus

@model NaviMenuEditModel
@{
    Layout = "_AdminHomeLayout";
    int ModuleId = (int)ViewBag.ModuleId;
    NaviMenuSearchModel searchModel = ViewBag.SearchModel as NaviMenuSearchModel ?? null;

    var availableStoresJsonStr = Html.Convert2JavascriptJsonString(searchModel.AvailableStores, true);

}

<div class="layui-card">
    <div class="layui-card-body">
        <div class="layui-collapse">
            <div class="layui-colla-item">
                <h2 class="layui-colla-title">条件查询</h2>
                <div class="layui-colla-content">
                    <form class="layui-form" action="">
                        <div class="layui-form-item">
                            <div class="layui-form-item layui-inline">
                                <label class="layui-form-label">@searchModel.DisplayName(m => m.SearchStoreId)</label>
                                <div class="layui-input-inline" style="width: 420px;">
                                    <input type="text" class="layui-hide" name="@searchModel.NameOf(m => m.SearchStoreId)" value="@searchModel.SearchStoreId.ToString()" />
                                    <div id="storeidselect" class="xmselect"></div>
                                </div>
                            </div>
                            <div class="layui-form-item layui-inline">
                                <label class="layui-form-label">@searchModel.DisplayName(m => m.LanguageCode)</label>
                                <div class="layui-input-inline">
                                    <input type="text" class="layui-hide" name="@searchModel.NameOf(m => m.LanguageCode)" value="@searchModel.LanguageCode.ToString()" />
                                    <select id="languageSelect" asp-items="@searchModel.AvailableLanguages" lay-filter="languageSelect">
                                    </select>
                                </div>
                            </div>
                            <input type="text" name="@searchModel.NameOf(m => m.Group)" value="@searchModel.Group.ToString()" class="layui-hide">
                        </div>
                        <div class="layui-form-item layui-inline">
                            <button id="searchBtn" class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="user-query">
                                <i class="layui-icon layui-icon-search"></i>
                                查询
                            </button>
                            <button type="reset" class="pear-btn pear-btn-md">
                                <i class="layui-icon layui-icon-refresh"></i>
                                重置
                            </button>
                        </div> 
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="layui-card">
    <div class="layui-card-body">
        <table id="pms-table" lay-filter="pms-table"></table>
    </div>
</div>
@await Component.InvokeAsync("ModuleButtonTemplet", new { moduleId = ModuleId, position = ModuleButtonGroup.HeadButtonsGroup })
@await Component.InvokeAsync("ModuleButtonTemplet", new { moduleId = ModuleId, position = ModuleButtonGroup.RecordButtonsGroup })

<input type="text" id="gridPageSize" value="@searchModel.AvailablePageSizes" class="layui-hide" />

<select id="LayoutTemplateTypesSelect" class="layui-hide">
    @foreach (var item in Html.GetEnumSelectList(typeof(LayoutTemplateType)))
    {
        <option value="@item.Value">@(item.Value.ToEnum<LayoutTemplateType>().GetDescription(true))</option>
    }
</select>

@section Scripts{
    <script type="text/javascript">
        layui.use(['table', 'jquery', 'form', 'element', 'lodash', 'xmSelect', 'Cookies', 'http', 'loading'], function () {
            let table = layui.table;
            let $ = layui.jquery;
            let form = layui.form;
            let element = layui.element;
            let lodash = layui.lodash;
            let xmSelect = layui.xmSelect;
            let Cookies = layui.Cookies;
            let http = layui.http;
            let loading = layui.loading;

            var getAuthToken = function () {
                const cookieVal = Cookies.get(".PMS.SignInToken");
                return cookieVal != null ? "Bearer " + cookieVal : "";
            };

            var layoutTemplateMaps = $.map($('#LayoutTemplateTypesSelect option'), function (item) {
                return {
                    value: PMSUtils.toInteger(item.value),
                    text: item.text
                }
            });
            //归属店铺多选下拉框
            var storeData = @Html.Raw(availableStoresJsonStr) ;
            var storeSelector = xmSelect.render({
                el: '#storeidselect',
                tips: '选择店铺',
                autoRow: true,
                height: 'auto',
                radio: true,
                clickClose: true,
                layVerify: 'required',
                layVerType: 'tips',
                data: PMSUtils.isString(storeData) ? $.parseJSON(storeData) : storeData,
                toolbar: { show: true },
                template({ item, sels, name, value }) {
                    return item.name + '<span style="position: absolute; right: 10px; color: #8799a3">' + item.url + '</span>'
                },
                on: function (data) {
                    var selectedStoreIds = lodash.map(data.arr, function (item) {
                        return PMSUtils.toNumber(item.value);
                    });
                    $("input[name=SearchStoreId]").val(lodash.join(selectedStoreIds));
                }
            });

            //语言查询
            form.on('select(languageSelect)', function (data) {
                $("input[name=LanguageCode]").val(data.value);
            });
            //列表条件过滤筛选
            var tableIns = null;
            form.on('submit(user-query)', function (data) {
                var queryData = data.field;
                if (PMSUtils.has(queryData, "select")) {
                    PMSUtils.remove(queryData, "select");
                }
                tableConfig.where = queryData;
                if (tableIns === null) {
                    var authToken = getAuthToken();
                    if (authToken.length > 0) {
                        tableConfig.headers = { 'Authorization': authToken };
                    }
                    tableIns = table.render(tableConfig);
                }
                else tableIns.reload(tableConfig, true);
                return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
            });
            let availabePageSize = PMSUtils.parseToIntegerArray($("#gridPageSize").val());
            var tableConfig = {
                id: 'pms-table',
                elem: '#pms-table',
                method: 'post',
                contentType: 'application/json;charset=UTF-8',
                url: backendwebapiConfig.loadpagednavimenu,
                request: {
                    pageName: '@searchModel.NameOf(p => p.Page)', //页码的参数名称，默认：page
                    limitName: '@searchModel.NameOf(p => p.PageSize)' //每页数据量的参数名，默认：limit
                },
                where: null,
                headers: null,
                limits: availabePageSize,
                limit:  @searchModel.PageSize,
                skin: 'line',
                toolbar: '#pmsHeadbarTpl',
                defaultToolbar: [{
                    layEvent: 'refresh',
                    icon: 'layui-icon-refresh',
                    title: '刷新'
                }, 'filter', 'print', 'exports'],
                page: {
                    curr: 1
                },
                cols: [
                    [
                        { field: 'Id', title: 'ID', width: 50, fixed: 'left', align: 'center' },
                        {
                            field: '@Model.NameOf(p => p.DisplayName)', title: '@Model.DisplayName(m => m.DisplayName)', width: 280
                            , templet: function (d) {
                                return '<span style="color: #555; font-weight: 600;">' + d.NaviMenuBreadcrumb + '</span>'
                        }
                        },
                        {
                            field: '@Model.NameOf(p => p.LayoutTemplateType)', title: '@Model.DisplayName(m => m.LayoutTemplateType)', width: 100
                            , templet: function (d) {
                                //console.log(d.LayoutTemplateType);
                                var item = lodash.find(layoutTemplateMaps, ['value', d.LayoutTemplateType]);
                                return item === undefined ? '未知布局' : item.text;
                            }
                        },
                        {
                            field: '@Model.NameOf(p => p.ShowOnHomepage)', title: '@Model.DisplayName(m => m.ShowOnHomepage)', width: 90, align: "center"
                            , templet: function (d) {
                                return d.ShowOnHomepage ? '显示' : "隐藏";
                            }
                        },
                        { field: '@Model.NameOf(p => p.UrlRoute)', title: '@Model.DisplayName(m => m.UrlRoute)', minWidth: 220},
                        {
                            field: '@Model.NameOf(p => p.IsActive)', title: '@Model.DisplayName(m => m.IsActive)', width: 100
                            , templet: function (d) {
                                return d.IsActive ? '正常' : "隐藏";
                            }
                        },
                        { field: '@Model.NameOf(p => p.DisplayOrder)', title: '@Model.DisplayName(m => m.DisplayOrder)', width: 80, align: "center" },
                        { title: '操作', templet: '#pmsRecordBarTpl', fixed: "right", align: 'center' }
                    ]
                ],
                error: function (e, msg) {
                    if (e.status === 401) { //UnAuthorized
                        var Error401 = http.ajax.defaultError401;
                        if (error.responseJSON) {
                            if (error.responseJSON.error !== undefined) {
                                Error401 = {
                                    message: error.responseJSON.error,
                                    details: error.responseJSON.error_description
                                };
                            }
                        }
                        http.ajax.showError(Error401);
                    }
                },
                parseData: function (res) {
                    return {
                        "code": res.state == 200 ? 0 : -1,     //解析接口状态
                        "msg": res.state == 200 ? "" : res.message,     //解析提示文本
                        "count": res.state == 200 ? res.data.RecordsTotal : 0, //解析数据长度
                        "data": res.state == 200 ? res.data.Data : null,   //解析数据列表
                    };
                }
            };

            $("#searchBtn").click();

            //监听顶部按钮栏
            let editWindowConfig = {
                title: "编辑/修改",
                type: 2,
                content: "",
                fixtolayoutbody: true,
                anim: 3,
                end: function () {
                    if (tableIns == null) {
                        window.location.reload(true);
                    } else {
                        $("#searchBtn").click();
                    }
                }
            };

            table.on('toolbar(pms-table)', function (obj) {
                if (obj.event === 'refresh') {
                    window.location.reload(true);
                    return;
                }
                const $btnElem = $(this);
                const isBtnDisabled = $btnElem.hasClass("layui-btn-disabled");
                if (isBtnDisabled) return false;
                const buttonId = $btnElem.data("buttonid");
                const moduleId = $btnElem.data("moduleid");
                if (obj.event === 'OnAdd') {
                    editWindowConfig.content = bakcendviewConfig.articlecolumndetaileditview + "?buttonid=" + buttonId + "&moduleid=" + moduleId;
                    PMSUtils.popupWindow(editWindowConfig);
                }
            });

            //监听表格数据行按钮
            table.on('tool(pms-table)', function (obj) {
                const data = obj.data;
                const $btnElem = $(this);
                const isBtnDisabled = $btnElem.hasClass("layui-btn-disabled");
                if (isBtnDisabled) return false;
                const buttonId = $btnElem.data("buttonid");
                const moduleId = $btnElem.data("moduleid");
                if (obj.event === 'OnEdit') {
                    editWindowConfig.content = bakcendviewConfig.articlecolumndetaileditview + "?buttonid=" + buttonId + "&moduleid=" + moduleId + "&menuid=" + data.Id;
                    PMSUtils.popupWindow(editWindowConfig);
                } else if (obj.event === 'OnDelete') {
                    alert("OnDelete");
                }
            });
        });
    </script>
}
